﻿using System;
using System.Collections.Generic;
 
using System.Text;
using System.Windows.Forms;
using HustQQModel;
namespace HustQQServer
{
    public class ServerEvt
    {
        public const String split = "$";

        public static OESServer Server = new OESServer();
        public ServerEvt()
        {
            Server.ReceivedTxt += new ClientEventHandel(Server_ReceivedTxt);
            Server.ReceivedMsg += new ClientEventHandel(Server_ReceivedMsg);
            Server.WrittenMsg += new ClientEventHandel(Server_WrittenMsg);
            Server.ReceiveDataReady += new ClientEventHandel(Server_ReceiveDataReady);
            Server.SendDataReady += new ClientEventHandel(Server_SendDataReady);
            Server.AcceptedClient += new EventHandler(Server_AcceptedClient);
            Server.StartServer();
        }

        void Server_WrittenMsg(Client client, string msg)
        {
            Console.Beep();
            Console.WriteLine("Sending:"+"(" + client.ClientIp + ")" + msg);
        }

        void Server_AcceptedClient(object sender, EventArgs e)
        {
            (sender as Client).DisConnect += new EventHandler(ServerEvt_DisConnect);
        }

        void ServerEvt_DisConnect(object sender, EventArgs e)
        {
            string rm = "";
            foreach (string k in connectRecord.Keys)
            {
                if (connectRecord[k] == sender as Client)
                {
                    rm = k;
                    break;
                }
            }
            if (rm != "" && sender!=null)
            {
                connectRecord.Remove(rm);
                fileList.Remove(sender as Client);
            }
        }

        void Server_ReceivedMsg(Client client, string msg)
        {
            Console.Beep();
            Console.WriteLine("Receiving:"+"("+client.ClientIp+")"+msg);
        }

        void Server_SendDataReady(Client client, string msg)
        {
            client.Port.FilePath = "D://FileTemp//" + fileList[client].FileId;
            
        }

        void Server_ReceiveDataReady(Client client, string msg)
        {
            client.Port.FilePath = "D://FileTemp//" + fileList[client].FileId;
            client.Port.fileLength = fileList[client].FileSize;
        }
       
        /// <summary>
        /// 登录用户
        /// </summary>
        Dictionary<String, Client> connectRecord = new Dictionary<string, Client>();

        /// <summary>
        /// 离线消息
        /// </summary>
        Dictionary<String, List<String>> messagesOffline = new Dictionary<String, List<String>>();

        Dictionary<Client,  FileInformation> fileList = new Dictionary<Client, FileInformation>();
        void Server_ReceivedTxt(Client client, string msg)
        {
            string[] msgs = msg.Split('$');
            switch (msgs[0])
            {
                case "Command":
                    {
                        switch(msgs[1])
                        {
                            #region 注册
                            case "Register":
                                {
                                    HustQQModel.User u = new HustQQModel.User();
                                    u.name = msgs[2];
                                    u.password = msgs[3];
                                    u.face = int.Parse(msgs[4]);
                                    u.age = int.Parse(msgs[5]);
                                    u.sex = int.Parse(msgs[6]);
                                    u.birthday = msgs[7];
                                    u.telephone = msgs[8];
                                    u.address = msgs[9];
                                    //获得一个随机的QQ号
                                    String Q = HustQQInterface.InterfaceManager.DataManager.Register(u);
                                    String replyRegister = "Reply" + split
                                           + "Register" + split
                                           + Q;
                                    client.SendTxt(replyRegister);
                                    break;
                                }
                            #endregion
                            #region 登陆
                            case "Login":
                                    {
                                        String Q = msgs[2];
                                        String password = msgs[3];
                                        String state = msgs[4]; //未考虑登陆状态
                                       
                                        String replyLogin = "Reply" + split
                                               + "Login";

                                        #region 文件传输初始化
                                        fileList.Add(client, null);
                                        #endregion

                                        if (connectRecord.ContainsKey(Q))//重复登陆，暂时定为不能登陆同一个账号
                                        {
                                            replyLogin += split + "Fail" + split + "重复登录";
                                        }
                                        bool pass = HustQQInterface.InterfaceManager.DataManager.Login(Q,password);
                                        if (pass)
                                        {
                                            replyLogin += split + "Success" + split + "";
                                            connectRecord.Add(Q, client);
                                            client.SendTxt(replyLogin);
                                            //处理离线消息
                                            List<String> myOfflineMessages = messagesOffline.ContainsKey(Q)?messagesOffline[Q]:null;
                                            if(myOfflineMessages!=null&&myOfflineMessages.Count != 0)
                                            {
                                                foreach (String myOfflineMessage in myOfflineMessages)
                                                {
                                                    Server_ReceivedTxt(client, myOfflineMessage);
                                                    myOfflineMessages.Remove(myOfflineMessage);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            replyLogin += split + "Fail" + split + "账号或密码错误";
                                            client.SendTxt(replyLogin);
                                        }
                                        break;
                                    }
                            #endregion
                            #region 退出
                            case "Logout":
                                    {
                                        String Q = msgs[2];
                                        String replyLogin = "Reply" + split
                                               + "Logout";

                                        if (!connectRecord.ContainsKey(Q))
                                        {
                                            MessageBox.Show("存在异常");
                                        }
                                        else
                                        {
                                            if (true)//一般情况直接退出
                                            {
                                                replyLogin += split + "Success" + split + "";
                                                connectRecord.Remove(Q);
                                                client.SendTxt(replyLogin);
                                                string rm = "";
                                                foreach (string k in connectRecord.Keys)
                                                {
                                                    if (connectRecord[k] == client)
                                                    {
                                                        rm = k;
                                                        break;
                                                    }
                                                }
                                                if (rm != "" && client != null)
                                                {
                                                    connectRecord.Remove(rm);
                                                    fileList.Remove(client);
                                                }
                                            }
                                            else
                                            {
                                                replyLogin += split + "Fail" + split + "error reason";
                                                client.SendTxt(replyLogin);
                                            }
                                        }
                                        break;
                                    }
                            #endregion

                            #region 获得好友列表,需要登陆后才能发送此消息
                            case "GetFriendList":
                                {
                                    String Q = msgs[2];
                                    if (connectRecord.ContainsKey(Q))
                                    {
                                        User user= HustQQInterface.InterfaceManager.DataManager.GetUserInformation(Q, true);
                                        String friendInfoList = "Reply" + split + "GetFriendList";
                                        foreach (User aFriend in user.friends)
                                        {
                                            friendInfoList += split
                                            
                                            + aFriend.qq_ID + split
                                            + aFriend.face.ToString() + split
                                            + aFriend.name + split
                                            + "" + split//好友备注
                                            + aFriend.note + split
                                            + aFriend.group;
                                            if (connectRecord.ContainsKey(aFriend.qq_ID))
                                            {
                                                friendInfoList += split + "T";
                                            }
                                            else
                                            {
                                                friendInfoList += split + "F";
                                            }
                                        }
                                        client.SendTxt(friendInfoList);
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                } 
                            #endregion
                            #region 获得群,需要登陆后才能发送此消息
                            case "GetTeam":
                                {
                                    String Q = msgs[2];
                                    if (connectRecord.ContainsKey(Q))
                                    {
                                        List<String> teams = HustQQInterface.InterfaceManager.DataManager.GetTeams(Q);
                                        String teamInfoList = "Reply" + split + "GetTeam";
                                        foreach (String t in teams)
                                        {
                                            HustQQModel.Team aTeam = HustQQInterface.InterfaceManager.DataManager.GetTeamInformation(t, false);
                                            teamInfoList += split + aTeam.teamID + split
                                            + aTeam.teamName + split
                                            + "";//群主
                                        }
                                        client.SendTxt(teamInfoList);
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                } 
                            #endregion
                            #region 获得群成员,需要登陆后才能发送此消息
                            case "GetTeamMember":
                                {
                                    String Q = msgs[2];
                                    String T = msgs[3];
                                    if (connectRecord.ContainsKey(Q))
                                    {
                                        List<String> members = HustQQInterface.InterfaceManager.DataManager.GetTeamInformation(T, true).members;
                                        String memberInfoList = "Reply" + split + "GetTeamMember";
                                        foreach (String m in members)
                                        {
                                            HustQQModel.User aMember = HustQQInterface.InterfaceManager.DataManager.GetUserInformation(m, false);
                                            memberInfoList +=split+
                                            aMember.qq_ID.Trim() + split
                                            + aMember.face.ToString() + split
                                            + aMember.name + split
                                            + aMember.note;
                                            if (connectRecord.ContainsKey(aMember.qq_ID))
                                            {
                                                memberInfoList += split + "T";
                                            }
                                            else
                                            {
                                                memberInfoList += split + "F";
                                            }    
                                        }
                                        client.SendTxt(memberInfoList);
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion

                            #region 查找个人信息
                            case "FindMyself":
                                {
                                    String Q = msgs[2];
                                    if (connectRecord.ContainsKey(Q))
                                    {
                                        HustQQModel.User me = HustQQInterface.InterfaceManager.DataManager.GetUserInformation(Q, true);
                                        String myInfoList = "Reply" +split
                                        +"FindMyself" + split
                                        + me.qq_ID + split
                                        + me.face.ToString() + split
                                        + me.name + split
                                        + me.note;//以后添加信息
                                        client.SendTxt(myInfoList);
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion
                            #region 查找好友
                            case "FindFriend":
                                {
                                    String Q = msgs[2];
                                    String findQNumber = msgs[3];
                                    if (connectRecord.ContainsKey(Q))
                                    {
                                        HustQQModel.User me = HustQQInterface.InterfaceManager.DataManager.GetUserInformation(findQNumber, false);
                                        String friendInfoList = "Reply" + split
                                        + "FindFriend" + split
                                        + me.qq_ID + split
                                        + me.face.ToString() + split
                                        + me.name + split
                                        + me.note;
                                        if (connectRecord.ContainsKey(findQNumber))
                                        {
                                            friendInfoList += split + "T";
                                        }
                                        else
                                        {
                                            friendInfoList += split + "F";
                                        }
                                        client.SendTxt(friendInfoList);
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion
                            #region 查找群组
                            case "FindTeam":
                                {
                                    String Q = msgs[2];
                                    String findTNumber = msgs[3];
                                    if (connectRecord.ContainsKey(Q))
                                    {
                                        HustQQModel.Team team = HustQQInterface.InterfaceManager.DataManager.GetTeamInformation(findTNumber, true);
                                        String teamInfoList = "Reply" + split
                                        + "FindTeam" + split
                                        + team.teamID + split
                                        + team.teamName;
                                        client.SendTxt(teamInfoList);
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion

                            #region 添加好友
                            case "AddFriend":
                                {
                                    String Q1 = msgs[2];
                                    String Q2 = msgs[3];
                                    String message = msgs[4];
                                    String group = msgs[5];
                                    String note = msgs[6];

                                    if (connectRecord.ContainsKey(Q1))
                                    {
                                        Client sendClient = connectRecord[Q1];
                                       
                                        if (connectRecord.ContainsKey(Q2))
                                        {
                                            Client receiveClient = connectRecord[Q2];
                                            String acceptFriendCommand = "Command" + split
                                                + "AcceptFriend" + split
                                                + Q1 + split
                                                + Q2 + split
                                                + message + split
                                                + group + split
                                                + note; ;
                                            receiveClient.SendTxt(acceptFriendCommand);
                                        }
                                        else
                                        {
                                            //离线消息处理
                                            if (messagesOffline[Q2] == null)
                                            {
                                                messagesOffline.Add(Q2, new List<string>());
                                            }
                                            messagesOffline[Q2].Add(msg);
                                        }
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion
                            #region 新建群
                            case "CreateTeam":
                                {
                                    String Q = msgs[2];
                                    String teamName = msgs[3];
                                    //获得一个随机的QQ号
                                    String T = HustQQInterface.InterfaceManager.DataManager.NewTeamToUser(Q,teamName);
                                    String replyCreateTeam = "Reply" + split
                                           + "CreateTeam" + split
                                           + teamName + split
                                           + T;
                                    client.SendTxt(replyCreateTeam);
                                    break;
                                }
                            #endregion
                            #region 加入群
                            case "AddTeam":
                                {
                                    String Q = msgs[2];
                                    String T = msgs[3];
                                    String message = msgs[4];
                                  
                                    if (connectRecord.ContainsKey(Q))
                                    {
                                        Client sendClient = connectRecord[Q];
                                        String tOwer = HustQQInterface.InterfaceManager.DataManager.GetTeamInformation(T, false).ower;
                                       
                                        if (connectRecord.ContainsKey(tOwer))
                                        {
                                            Client receiveClient = connectRecord[tOwer];
                                            String acceptFriendCommand = "Command" + split
                                                + "AcceptTeamMember" + split
                                                + Q + split
                                                + T + split
                                                + message;
                                            receiveClient.SendTxt(acceptFriendCommand);
                                        }
                                        else
                                        {
                                            //离线消息处理
                                            if (messagesOffline[tOwer] == null)
                                            {
                                                messagesOffline.Add(tOwer, new List<string>());
                                            }
                                            messagesOffline[tOwer].Add(msg);
                                        }
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion

                            #region 转发一对一消息，需要登陆后才能发送此消息
                            case "SendMessage":
                                {
                                    String time = msgs[2];
                                    String Q1 = msgs[3];
                                    String Q2 = msgs[4];
                                    String message = msgs[5];
                                   
                                    if (connectRecord.ContainsKey(Q1))
                                    {
                                        Client sendClient = connectRecord[Q1];                  
                                        if (connectRecord.ContainsKey(Q2))
                                        {
                                            Client receiveClient = connectRecord[Q2];
                                            String receiveCommand = "Command" + split
                                                + "ReceiveMessage" + split
                                                + Q1 + split
                                                + message + split
                                                + time;
                                            receiveClient.SendTxt(receiveCommand);
                                        }
                                        else
                                        {
                                            //离线消息处理
                                            if (messagesOffline[Q1] == null)
                                            {
                                                messagesOffline.Add(Q1, new List<string>());
                                            }
                                            messagesOffline[Q1].Add(msg);
                                        }
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion
                            #region 转发群消息，需要登陆后才能发送此消息
                            case "SendTeamMessage":
                                {
                                    String time = msgs[2];
                                    String Q = msgs[3];
                                    String T = msgs[4];
                                    String message = msgs[5];
                                    if (connectRecord.ContainsKey(Q))
                                    {
                                        HustQQModel.Team team = HustQQInterface.InterfaceManager.DataManager.GetTeamInformation(T, true);
                                        foreach (String teamMember in team.members)
                                        {

                                            if (connectRecord.ContainsKey(teamMember) && Q!=teamMember)
                                            {
                                                Client receiveClient = connectRecord[teamMember];
                                                String receiveCommand = "Command" + split
                                                + "ReceiveTeamMessage" + split
                                                + T + split
                                                + Q + split
                                                + message + split
                                                + time;
                                                receiveClient.SendTxt(receiveCommand);
                                            }
                                            else
                                            {
                                                //处理离线消息
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion

                            #region 文件图片传输
                            case "SendFile":
                                {
                                    fileList[client]= new FileInformation(msgs[4], long.Parse(msgs[5]), Guid.Parse(msgs[6]),msgs[2],msgs[3]);
                                    
                                    Client remoteClient = connectRecord[msgs[3]];
                                    fileList[remoteClient] = new FileInformation(msgs[4], long.Parse(msgs[5]), Guid.Parse(msgs[6]), msgs[2], msgs[3]);
                                    remoteClient.SendTxt(msg);
                                    break;
                                }
                            case "SendOver":
                                {
                                    Client remoteClient = connectRecord[msgs[3]];
                                    remoteClient.SendTxt(msg);
                                    break;
                                }
                            case "ReceiveOver":
                                {
                                    Client remoteClient = connectRecord[msgs[3]];
                                    remoteClient.SendTxt(msg);
                                    break;
                                }
                            #endregion
                        }
                        break;
                    }
               
                case "Reply":
                    {
                        switch (msgs[1])
                        {
                            #region 回复添加好友
                            case "AcceptFriend":
                                {
                                    String Q1 = msgs[2];
                                    String Q2 = msgs[3];
                                    String result = msgs[4];
                                    String message = msgs[5];
                                    String group1 = msgs[6];
                                    String note1 = msgs[7];
                                    String group2 = msgs[8];
                                    String note2 = msgs[9];

                                    if (connectRecord.ContainsKey(Q2))
                                    {  
                                        Client sendClient = connectRecord[Q2];                                       
                                        if (connectRecord.ContainsKey(Q1))
                                        {
                                            Client receiveClient = connectRecord[Q1];
                                            HustQQInterface.InterfaceManager.DataManager.AddFriendToUser(Q1, Q2);
                                            HustQQInterface.InterfaceManager.DataManager.AddFriendToUser(Q2, Q1);
                                            String acceptFriendCommand = "Reply" + split
                                                + "AddFriend" + split
                                                + Q2 + split
                                                + result + split
                                                + message + split
                                                + group1 + split
                                                + note1;
                                            receiveClient.SendTxt(acceptFriendCommand);
                                        }
                                        else
                                        {
                                            //离线消息处理
                                            if (messagesOffline[Q1] == null)
                                            {
                                                messagesOffline.Add(Q1, new List<string>());
                                            }
                                            messagesOffline[Q1].Add(msg);
                                        }
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion
                            #region 回复添加入群
                            case "AcceptTeamMember":
                                {
                                    String Q = msgs[2];
                                    String T = msgs[3];
                                    String result = msgs[4];
                                    String message = msgs[5];

                                    String tOwer = HustQQInterface.InterfaceManager.DataManager.GetTeamInformation(T, false).ower;
                                   
                                    if (connectRecord.ContainsKey(tOwer))
                                    {
                                        Client sendClient = connectRecord[tOwer]; 
                                        if (connectRecord.ContainsKey(Q))
                                        {
                                            Client receiveClient = connectRecord[Q];
                                            HustQQInterface.InterfaceManager.DataManager.AddFriendToTeam(T, Q);
                                            String acceptTeamMember = "Reply" + split
                                                + "AddTeam" + split
                                                + T + split
                                                + result + split
                                                + message;
                                            receiveClient.SendTxt(acceptTeamMember);
                                        }
                                        else
                                        {
                                            //离线消息处理
                                            if (messagesOffline[Q] == null)
                                            {
                                                messagesOffline.Add(Q, new List<string>());
                                            }
                                            messagesOffline[Q].Add(msg);
                                        }
                                    }
                                    else
                                    {
                                        //非法攻击处理
                                    }
                                    break;
                                }
                            #endregion
                            #region 文件图片回复
                            case "SendFile":
                                {
                                    Client remoteClient = connectRecord[msgs[2]];
                                    remoteClient.SendTxt(msg);
                                    break;
                                }
                            #endregion
                        }   
                        break;
                    }
            }
        }
    }
}
